package com.mzj.saas.jobs.backlog.service;

import com.mzj.saas.commons.enums.BacklogItemTypeEnum;
import com.mzj.saas.jobs.backlog.entity.BacklogItem;
import com.mzj.saas.jobs.backlog.entity.BacklogItemUnOpen;
import com.mzj.saas.jobs.backlog.repository.BacklogItemRepository;
import com.mzj.saas.jobs.backlog.repository.BacklogItemUnOpenRepository;
import com.mzj.saas.jobs.backlog.vo.BacklogUnOpenVO;
import com.mzj.saas.jobs.bill.entity.AppUser;
import com.mzj.saas.jobs.bill.entity.CommunityHouseUser;
import com.mzj.saas.jobs.bill.repository.AppUserRepository;
import com.mzj.saas.jobs.bill.repository.CommunityHouseUserRepository;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

/**
 * 待办事项
 */
@Service
public class BacklogUnOpenService {
    private static Logger log = LoggerFactory.getLogger(BacklogUnOpenService.class);

    @Autowired
    private JdbcTemplate jdbcTemplate;
    @Autowired
    private BacklogItemRepository backlogItemRepository;
    @Autowired
    private BacklogItemUnOpenRepository backlogItemUnOpenRepository;
    @Autowired
    private AppUserRepository appUserRepository;
    @Autowired
    private CommunityHouseUserRepository communityHouseUserRepository;

    public String work() throws Exception {
        handleBacklogUnOpen();
        return "SUCCESS";
    }

    public void handleBacklogUnOpen() {
        try {
            log.info("BacklogUnOpenService----->未开门提醒待办事项");

            String sql = "SELECT fs.lock_id AS lockId,fs.close_day AS closeDay,fs.close_remind_content AS closeRemindContent,\n" +
                    "os.open_day AS openDay,l.house_id as houseId,l.match_user_id as matchUserId \n" +
                    "FROM saas_house_lock_frozen_set fs \n" +
                    "LEFT JOIN saas_house_lock_open_statistics os ON fs.lock_id = os.lock_id  \n" +
                    "LEFT JOIN saas_smart_lock l ON fs.lock_id = l.id  \n" +
                    "WHERE l.id IS NOT NULL AND os.open_day >= fs.close_day";

            List<BacklogUnOpenVO> list = jdbcTemplate.query(sql, new BeanPropertyRowMapper<>(BacklogUnOpenVO.class));
            if (list.isEmpty()) {
                log.info("BacklogUnOpenService----->没有未开门天数超过设置天数，无需提醒");
                return;
            }

            log.info("BacklogUnOpenService----->未开门提醒 size = {}", list.size());

            Date date = new Date();
            for (BacklogUnOpenVO vo : list) {
                BacklogItem backlogItem = new BacklogItem();
                backlogItem.setHouseId(vo.getHouseId());
                backlogItem.setType(BacklogItemTypeEnum.CLOSE_REMIND.getValue());
                backlogItem.setTitle("未开门提醒");
                backlogItem.setContent(vo.getCloseRemindContent());
                backlogItem.setHandleStatus(0);
                backlogItem.setMatchUserId(vo.getMatchUserId());
                if (StringUtils.isNotEmpty(vo.getMatchUserId())) {
                    AppUser appUsers = appUserRepository.findByIdOrEnterpriseUserId(vo.getMatchUserId(), vo.getMatchUserId());
                    if (appUsers != null) {
                        backlogItem.setPhone(appUsers.getPhone());
                    }
                } else {
                    List<CommunityHouseUser> communityHouseUserList = communityHouseUserRepository.findByCommunityHouseIdAndStatusAndType(vo.getHouseId(), 1, 1);
                    if (communityHouseUserList != null && communityHouseUserList.size() > 0) {
                        backlogItem.setMatchUserId(communityHouseUserList.get(0).getUserId());//承租人ID
                        backlogItem.setPhone(communityHouseUserList.get(0).getMobile());//电话
                    }
                }
                backlogItem.setCreateTime(date);
                BacklogItem save = backlogItemRepository.save(backlogItem);

                BacklogItemUnOpen unOpen = new BacklogItemUnOpen();
                unOpen.setBacklogItemId(save.getId());
                unOpen.setMatchUserId(vo.getMatchUserId());
                backlogItemUnOpenRepository.save(unOpen);
            }

            log.info("BacklogUnOpenService----->未开门提醒结束");
        } catch (Exception e) {
            log.error("未开门提醒异常  " + e.getMessage(), e);
        }
    }

}
